package com.toocms.jinjuhang.ui.commodity.evaluate

import android.app.Application
import android.os.Bundle
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.data.goods.GoodsCommentsData
import com.toocms.jinjuhang.ui.system.EvaluateItemModel
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.event.SingleLiveEvent

class CommodityEvaluateModel(application: Application, val bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {
    var p = 1
    val goodsId by lazy {
        bundle?.getString(Constants.BundleKey.KEY_GOODS_ID)
    }

    val items = ObservableArrayList<EvaluateItemModel>()
    val itemBinding =
        ItemBinding.of<EvaluateItemModel>(BR.evaluateItemModel, R.layout.item_evaluate)

    val stopRefreshOrLoadSingleLiveEvent = SingleLiveEvent<Unit>()

    val refreshBindingCommand = BindingCommand<BindingAction>(BindingAction {
        p = 1
        loadData(p)
    })
    val loadBindingCommand = BindingCommand<BindingAction>(BindingAction {
        p++
        loadData(p)
    })

    init {
        loadData(isShowLoading = true)
    }

    private fun loadData(p: Int = 1, isShowLoading: Boolean = false) {
        val params = mutableMapOf<String, String?>()
        params["goods_id"] = goodsId
        params["page_size"] = "15"
        params["p"] = p.toString()
        requestData(
            Urls.Goods.GOODS_COMMENTS,
            params,
            resultClass = GoodsCommentsData::class.java,
            isShowLoading = isShowLoading,
            result = {
                if (1 == p) items.clear()
                it.list?.forEach {
                    items += EvaluateItemModel(this, ObservableField(it))
                }
            },
            finish = {
                stopRefreshOrLoadSingleLiveEvent.call()
            })
    }

}